"""
版本状态流转相关数据库索引初始化脚本
"""
from motor.motor_asyncio import AsyncIOMotorDatabase  # pyright: ignore[reportMissingImports]
import logging

logger = logging.getLogger(__name__)


async def init_version_transition_indexes(db: AsyncIOMotorDatabase):
    """
    初始化版本状态流转相关的数据库索引
    
    Args:
        db: 数据库连接
    """
    try:
        # 1. 版本状态流转审批表索引
        try:
            await db.version_transition_approvals.create_index(
                [("version_id", 1), ("status", 1)],
                name="version_id_status_idx"
            )
            logger.info("创建索引: version_transition_approvals.version_id_status_idx")
        except Exception as e:
            logger.warning(f"创建索引失败（可能已存在）: {e}")
        
        try:
            await db.version_transition_approvals.create_index(
                [("requester_id", 1), ("status", 1), ("requested_at", -1)],
                name="requester_status_requested_idx"
            )
            logger.info("创建索引: version_transition_approvals.requester_status_requested_idx")
        except Exception as e:
            logger.warning(f"创建索引失败（可能已存在）: {e}")
        
        try:
            await db.version_transition_approvals.create_index(
                [("approvers.user_id", 1), ("status", 1)],
                name="approver_user_status_idx"
            )
            logger.info("创建索引: version_transition_approvals.approver_user_status_idx")
        except Exception as e:
            logger.warning(f"创建索引失败（可能已存在）: {e}")
        
        # 2. 版本状态流转历史表索引（如果表存在）
        try:
            await db.version_status_history.create_index(
                [("version_id", 1), ("created_at", -1)],
                name="version_id_created_idx"
            )
            logger.info("创建索引: version_status_history.version_id_created_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（表可能不存在）: {e}")
        
        try:
            await db.version_status_history.create_index(
                [("transition_type", 1), ("created_at", -1)],
                name="transition_type_created_idx"
            )
            logger.info("创建索引: version_status_history.transition_type_created_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（表可能不存在）: {e}")
        
        # 3. 版本关联表索引（如果还没有）
        try:
            await db.version_task_relations.create_index(
                [("version_id", 1), ("task_id", 1)],
                name="version_task_unique_idx",
                unique=True
            )
            logger.info("创建索引: version_task_relations.version_task_unique_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        try:
            await db.version_defect_relations.create_index(
                [("version_id", 1), ("defect_id", 1)],
                name="version_defect_unique_idx",
                unique=True
            )
            logger.info("创建索引: version_defect_relations.version_defect_unique_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        try:
            await db.version_requirement_relations.create_index(
                [("version_id", 1), ("requirement_id", 1)],
                name="version_requirement_unique_idx",
                unique=True
            )
            logger.info("创建索引: version_requirement_relations.version_requirement_unique_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        logger.info("版本状态流转相关索引初始化完成")
        
    except Exception as e:
        logger.error(f"初始化版本状态流转索引失败: {str(e)}", exc_info=True)

